﻿using System;
using System.Configuration;
using log4net;

namespace Jiubang.Communication.Common {
    public sealed class ConfigurationReader {
        private readonly Configuration config;
        private readonly ILog log;

        public ConfigurationReader(Configuration config) {
            if (config == null)
                throw new ArgumentNullException();

            log = LogManager.GetLogger(GetType());
            this.config = config;
        }

        public int GetInt32(string key, int defaultValue) {
            var setting = config.AppSettings.Settings[key];

            if (setting != null) {
                int value;
                if (int.TryParse(setting.Value, out value))
                    return value;

                log.InfoFormat("{0}项值[{1}]无法正确解释，默认为{2}", key, setting.Value, defaultValue);
                return defaultValue;
            }
            log.InfoFormat("{0}项未设置，默认为{1}", key, defaultValue);
            return defaultValue;
        }

        public bool GetBoolean(string name) {
            var setting = config.AppSettings.Settings[name];
            if (setting != null) {
                bool value;
                if (!bool.TryParse(setting.Value, out value))
                    log.InfoFormat("{0}项值[{1}]无法正确解释，默认为{2}", name, setting.Value, false);
                return value;
            }
            log.InfoFormat("{0}项未设置，默认为{1}", name, false);
            return false;
        }

        public string GetString(string name, string defaultValue) {
            var setting = config.AppSettings.Settings[name];
            if (setting != null) {
                return setting.Value;
            }
            log.InfoFormat("{0}项未设置，默认为{1}", name, defaultValue);
            return defaultValue;
        }
    }
}